import { Component, OnInit, ViewChild } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema } from '@delon/form';
import { UserService } from '../../../../service/user/user.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { deepCopy } from '@delon/util';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { CommService } from '../../../../service/comm/comm.service';
import { ServiceResult } from '@core/constant';

@Component({
  selector: 'agent-user-list-edit',
  templateUrl: './edit.component.html',
  styles: [`:host ::ng-deep .ant-form-item { 
      margin-bottom: 12px;
  }`],
  providers: [TranslatePipe]
})
export class AgentUserListEditComponent implements OnInit {
  record: any = {};
  userInfo = null;
  brands = [];
  listOfSelectedValue = [];
  currencys = [];
  sitecodes = [];
  labels = [];
  loading = false;
  constructor(
    private trans: TranslateService,
    private transPipe: TranslatePipe,
    private msg: NzMessageService,
    private user: UserService,
    private modal: NzModalRef,
    public msgSrv: NzMessageService,
    public http: _HttpClient,
    private comm: CommService
  ) {}

  ngOnInit(): void {
    if (this.record.id) {
      this.user.info(this.record.id).pipe(
        catchError(err => { return of(err); })
      ).subscribe(ret=>{
        if (ret.status === 200) {
            const data = ret.data;
            this.record = data;

            this.userInfo = JSON.parse(this.record.userId);
            if (typeof this.userInfo === 'object' && this.userInfo) {
                this.record.userId = this.userInfo.id;
            }
            this.listOfSelectedValue = this.record.brand.split(',');
        } else {
            this.msg.error(ret.message);
        }
      });
    }
    this.loadBrands();
    this.loadCurrency();
    this.loadSiteCode();
    this.loadLabels();
  }

  loadBrands() {
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
            this.brands.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
        }
      }
    })
  }

  loadLabels() {
    this.labels = [];
    this.comm.getLabels().subscribe(data => {
        const ret: ServiceResult = <ServiceResult> data;
        if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.labels.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
          }
        }
    })
  }

  loadCurrency() {
      this.currencys = [];
      this.comm.getCurrencys().subscribe(data => {
          const ret: ServiceResult = <ServiceResult> data;
          if (ret.status === 200) {
            for (const row of ret['data']['rows']) {
                this.currencys.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
            }
          }
      })
  }

  loadSiteCode() {
    this.sitecodes = [];
    this.comm.getSiteCodes().subscribe(data => {
        const ret: ServiceResult = <ServiceResult> data;
        if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.sitecodes.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
          }
        }
    })
  }

  save() {
    let userForm = deepCopy(this.record);
    let lang = this.trans.currentLang || this.trans.defaultLang;
    if (!userForm.name) {
        if (lang === 'en') {
            this.msg.warning('This name is required');
        } else {
            this.msg.warning('名称');
        }
        return;
    }

    if (!userForm.username) {
        this.msg.warning(lang === 'en' ? 'This account is required' : '账号');
        return;
    }

    if ("admin" === userForm.username) {
        this.msg.warning('不能以"admin"作为账户名');
        return;
    }

    if (!userForm.id && !userForm.password) {
        this.msg.warning(lang === 'en' ? 'This password is required' : '密码不能空');
        return;
    }
    if (!userForm.id && (userForm.password.length < 4 || userForm.password.length > 16)) {
        this.msg.warning(lang === 'en' ? 'Password must have at least 4 characters' : '密码长度需4-16个字符');
        return;
    }
    if (this.listOfSelectedValue.length === 0) {
        this.msg.warning(lang === 'en' ? 'This brand is required' : '请选择品牌');
        return;
    }
    if (!userForm.currency) {
        this.msg.warning(lang === 'en' ? 'The currency is required' : '币种不能空');
        return;
    }
    if (!userForm.siteCode) {
        this.msg.warning(lang === 'en' ? 'The sitecode is required' : '公司代码不能空');
        return;
    }

    userForm.level = "FIRST";
    userForm.account = userForm.username;
    userForm.brand = this.listOfSelectedValue.toString();
    this.loading = true;
    if (userForm.id) {
        this.user.modify(userForm).pipe(
            catchError(err => {
                return of(err)
            })
        ).subscribe(ret => {
            this.loading = false;
            if (ret.status == 200) {
                this.msg.success(lang === 'en' ? 'Save successful' : '操作成功');
                this.close();
            } else {
                this.msg.error(ret.message);
            }
        })
    } else {
        this.user.add(userForm).pipe(
            catchError(err => {
                return of(err);
            })
        ).subscribe(ret => {
            this.loading = false;
            if (ret.status == 200) {
                this.msg.success(lang === 'en' ? 'Save successful' : '操作成功');
                this.close();
            } else {
                this.msg.error(ret.message);
            }
        })
    }
  }

  close() {
    this.modal.close(true);
    this.modal.destroy();
  }
}
